package com.neusoft.elm.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.neusoft.elm.po.Business;
import com.neusoft.elm.service.BusinessService;
import com.neusoft.elm.service.impl.BusinessServiceImpl;

/**
 * 根据排序类型查询商家列表Servlet
 * 对应原BusinessController的listBusinessBySort方法
 */
@WebServlet("/api/BusinessController/listBusinessBySort")
public class ListBusinessBySortServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置编码和响应类型
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        
        // 添加CORS支持
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
        
        PrintWriter out = response.getWriter();
        ObjectMapper om = new ObjectMapper();
        
        try {
            System.out.println("BusinessController: 按排序类型查询商家");
            
            String sortType = request.getParameter("sortType");
            
            // 参数验证
            if (sortType == null || sortType.trim().isEmpty()) {
                sortType = "distance"; // 默认按距离排序
            }
            
            System.out.println("接收到排序类型: " + sortType);
            
            // 验证排序类型
            if (!isValidSortType(sortType)) {
                System.out.println("无效的排序类型: " + sortType);
                sortType = "distance";
            }
            
            BusinessService service = new BusinessServiceImpl();
            List<Business> list = service.listBusinessBySort(sortType);
            
            System.out.println("Controller: 按 " + sortType + " 排序查询到 " + list.size() + " 个商家");
            
            // 打印前几个商家信息用于调试
            for (int i = 0; i < Math.min(3, list.size()); i++) {
                Business business = list.get(i);
                System.out.println("商家" + (i+1) + ": " + business.getBusinessName() + 
                                 " - 距离:" + business.getDistance() + 
                                 " - 销量:" + business.getMonthlySales() + 
                                 " - 评分:" + business.getRating());
            }
            
            // 返回JSON响应
            out.print(om.writeValueAsString(list));
            
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.print("{\"error\":\"服务器内部错误：" + e.getMessage() + "\"}");
        } finally {
            out.close();
        }
    }
    
    /**
     * 验证排序类型是否有效
     */
    private boolean isValidSortType(String sortType) {
        return "distance".equals(sortType) || 
               "sales".equals(sortType) || 
               "rating".equals(sortType);
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doPost(request, response);
    }
    
    @Override
    protected void doOptions(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 处理预检请求
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setStatus(HttpServletResponse.SC_OK);
    }
}